<template>
  <el-dialog
    title="分配权限"
    v-model="visible"
    width="400px"
    append-to-body
    @closed="$emit('update:visible', false)"
  >
    <el-tree
      ref="treeRef"
      :data="menuTree"
      show-checkbox
      node-key="id"
      :props="{ label: 'name', children: 'children' }"
      :default-checked-keys="checkedKeys"
    />
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { request } from '@/utils/request'

const props = defineProps({
  roleId: {
    type: Number,
    required: true
  },
  visible: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'success'])

const menuTree = ref([])
const checkedKeys = ref([])
const treeRef = ref(null)

// 获取菜单树
const getMenuTree = async () => {
  try {
    const res = await request('/api/menu/tree')
    if (res.code === 200) {
      menuTree.value = res.data
    }
  } catch (error) {
    console.error('获取菜单树失败:', error)
  }
}

// 获取角色的菜单权限
const getRoleMenus = async () => {
  try {
    const res = await request(`/api/menu/role/${props.roleId}`)
    if (res.code === 200) {
      checkedKeys.value = res.data
    }
  } catch (error) {
    console.error('获取角色菜单失败:', error)
  }
}

// 提交权限配置
const handleSubmit = async () => {
  if (!treeRef.value) return
  
  const checkedNodes = treeRef.value.getCheckedKeys()
  const halfCheckedNodes = treeRef.value.getHalfCheckedKeys()
  const menuIds = [...checkedNodes, ...halfCheckedNodes]
  
  try {
    const res = await request(`/api/menu/role/${props.roleId}`, {
      method: 'PUT',
      body: menuIds
    })
    
    if (res.code === 200) {
      ElMessage.success('权限配置成功')
      emit('success')
      emit('update:visible', false)
    }
  } catch (error) {
    console.error('配置权限失败:', error)
  }
}

watch(() => props.visible, (val) => {
  if (val) {
    getMenuTree()
    getRoleMenus()
  }
})
</script> 